﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Security.Cryptography;



namespace Dt261.ble
{



    public class BleCore

    {
        //public enum MsgType
        //{
        //    NotifyTxt,
        //    BleData
        //}
        //private Boolean asyncLock = false;



        ///// <summary>

        ///// 搜索蓝牙设备对象

        ///// </summary>

        //private DeviceWatcher deviceWatcher;



        ///// <summary>

        ///// 当前连接的服务

        ///// </summary>

        //public GattDeviceService CurrentService { get; set; }



        ///// <summary>

        ///// 当前连接的蓝牙设备

        ///// </summary>

        //public BluetoothLEDevice CurrentDevice { get; set; }



        ///// <summary>

        ///// 写特征对象

        ///// </summary>

        //public GattCharacteristic CurrentWriteCharacteristic { get; set; }



        ///// <summary>

        ///// 通知特征对象

        ///// </summary>

        //public GattCharacteristic CurrentNotifyCharacteristic { get; set; }



        ///// <summary>

        ///// 特性通知类型通知启用

        ///// </summary>

        //private const GattClientCharacteristicConfigurationDescriptorValue CHARACTERISTIC_NOTIFICATION_TYPE = GattClientCharacteristicConfigurationDescriptorValue.Notify;



        ///// <summary>

        ///// 存储检测到的设备

        ///// </summary>

        //private List<BluetoothLEDevice> DeviceList = new List<BluetoothLEDevice>();



        ///// <summary>

        ///// 定义搜索蓝牙设备委托

        ///// </summary>

        //public delegate void DeviceWatcherChangedEvent(MsgType type, BluetoothLEDevice bluetoothLEDevice);



        ///// <summary>

        ///// 搜索蓝牙事件

        ///// </summary>

        //public event DeviceWatcherChangedEvent DeviceWatcherChanged;



        ///// <summary>

        ///// 获取服务委托

        ///// </summary>

        //public delegate void GattDeviceServiceAddedEvent(GattDeviceService gattDeviceService);



        ///// <summary>

        ///// 获取服务事件

        ///// </summary>

        //public event GattDeviceServiceAddedEvent GattDeviceServiceAdded;



        ///// <summary>

        ///// 获取特征委托

        ///// </summary>

        //public delegate void CharacteristicAddedEvent(GattCharacteristic gattCharacteristic);



        ///// <summary>

        ///// 获取特征事件

        ///// </summary>

        //public event CharacteristicAddedEvent CharacteristicAdded;



        ///// <summary>

        ///// 提示信息委托

        ///// </summary>

        //public delegate void MessAgeChangedEvent(MsgType type, string message, byte[] data = null);



        ///// <summary>

        ///// 提示信息事件

        ///// </summary>

        //public event MessAgeChangedEvent MessAgeChanged;



        ///// <summary>

        ///// 当前连接的蓝牙Mac

        ///// </summary>

        //private string CurrentDeviceMAC { get; set; }



        //public BleCore()

        //{



        //}



        ///// <summary>

        ///// 搜索蓝牙设备

        ///// </summary>

        //public void StartBleDeviceWatcher()

        //{

        //    string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" };

        //    string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";



        //    this.deviceWatcher =

        //            DeviceInformation.CreateWatcher(

        //                aqsAllBluetoothLEDevices,

        //                requestedProperties,

        //                DeviceInformationKind.AssociationEndpoint);



        //    // Register event handlers before starting the watcher.

        //    this.deviceWatcher.Added += this.DeviceWatcher_Added;

        //    this.deviceWatcher.Stopped += this.DeviceWatcher_Stopped;

        //    this.deviceWatcher.Start();

        //    string msg = "自动发现设备中..";



        //    this.MessAgeChanged(MsgType.NotifyTxt, msg);

        //}



        ///// <summary>

        ///// 停止搜索蓝牙

        ///// </summary>

        //public void StopBleDeviceWatcher()

        //{

        //    this.deviceWatcher.Stop();

        //}



        ///// <summary>

        ///// 获取发现的蓝牙设备

        ///// </summary>

        ///// <param name="sender"></param>

        ///// <param name="args"></param>

        //private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)

        //{

        //    this.MessAgeChanged(MsgType.NotifyTxt, "发现设备:" + args.Id);

        //    this.Matching(args.Id);

        //}



        ///// <summary>

        ///// 停止搜索蓝牙设备

        ///// </summary>

        ///// <param name="sender"></param>

        ///// <param name="args"></param>

        //private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)

        //{

        //    string msg = "自动发现设备停止";

        //    this.MessAgeChanged(MsgType.NotifyTxt, msg);

        //}



        ///// <summary>

        ///// 匹配

        ///// </summary>

        ///// <param name="Device"></param>

        //public void StartMatching(BluetoothLEDevice Device)

        //{

        //    this.CurrentDevice = Device;

        //}



        ///// <summary>

        ///// 获取蓝牙服务

        ///// </summary>

        //public async void FindService()

        //{

        //    var GattServices = this.CurrentDevice.GattServices;

        //    foreach (GattDeviceService ser in GattServices)

        //    {

        //        this.GattDeviceServiceAdded(ser);

        //    }

        //}



        ///// <summary>

        ///// 获取特性

        ///// </summary>

        //public async void FindCharacteristic(GattDeviceService gattDeviceService)

        //{

        //    this.CurrentService = gattDeviceService;

        //    foreach (var c in gattDeviceService.GetAllCharacteristics())

        //    {

        //        this.CharacteristicAdded(c);

        //    }

        //}



        ///// <summary>

        ///// 获取操作

        ///// </summary>

        ///// <returns></returns>

        //public async Task SetOpteron(GattCharacteristic gattCharacteristic)

        //{

        //    if (gattCharacteristic.CharacteristicProperties == GattCharacteristicProperties.Write)

        //    {

        //        this.CurrentWriteCharacteristic = gattCharacteristic;

        //    }

        //    if (gattCharacteristic.CharacteristicProperties == GattCharacteristicProperties.Notify)

        //    {

        //        this.CurrentNotifyCharacteristic = gattCharacteristic;

        //    }

        //    if ((uint)gattCharacteristic.CharacteristicProperties == 26)

        //    { }



        //    if (gattCharacteristic.CharacteristicProperties == (GattCharacteristicProperties.Notify | GattCharacteristicProperties.Read | GattCharacteristicProperties.Write))

        //    {

        //        this.CurrentWriteCharacteristic = gattCharacteristic;



        //        this.CurrentNotifyCharacteristic = gattCharacteristic;

        //        this.CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;

        //        this.CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;

        //        await this.EnableNotifications(CurrentNotifyCharacteristic);

        //    }



        //    this.Connect();

        //}



        ///// <summary>

        ///// 连接蓝牙

        ///// </summary>

        ///// <returns></returns>

        //private async Task Connect()

        //{

        //    byte[] _Bytes1 = BitConverter.GetBytes(this.CurrentDevice.BluetoothAddress);

        //    Array.Reverse(_Bytes1);

        //    this.CurrentDeviceMAC = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();



        //    string msg = "正在连接设备<" + this.CurrentDeviceMAC + ">..";

        //    this.MessAgeChanged(MsgType.NotifyTxt, msg);

        //    this.CurrentDevice.ConnectionStatusChanged += this.CurrentDevice_ConnectionStatusChanged;

        //}



        ///// <summary>

        ///// 搜索到的蓝牙设备

        ///// </summary>

        ///// <returns></returns>

        //private async Task Matching(string Id)

        //{

        //    try

        //    {

        //        BluetoothLEDevice.FromIdAsync(Id).Completed = async (asyncInfo, asyncStatus) =>

        //        {

        //            if (asyncStatus == AsyncStatus.Completed)

        //            {

        //                BluetoothLEDevice bleDevice = asyncInfo.GetResults();

        //                this.DeviceList.Add(bleDevice);

        //                this.DeviceWatcherChanged(MsgType.BleData, bleDevice);

        //            }

        //        };

        //    }

        //    catch (Exception e)

        //    {

        //        string msg = "没有发现设备" + e.ToString();

        //        this.MessAgeChanged(MsgType.NotifyTxt, msg);

        //        this.StartBleDeviceWatcher();

        //    }

        //}



        ///// <summary>

        ///// 主动断开连接

        ///// </summary>

        ///// <returns></returns>

        //public void Dispose()

        //{



        //    CurrentDeviceMAC = null;

        //    CurrentService?.Dispose();

        //    CurrentDevice?.Dispose();

        //    CurrentDevice = null;

        //    CurrentService = null;

        //    CurrentWriteCharacteristic = null;

        //    CurrentNotifyCharacteristic = null;

        //    MessAgeChanged(MsgType.NotifyTxt, "主动断开连接");

        //}



        //private void CurrentDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)

        //{

        //    if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected && CurrentDeviceMAC != null)

        //    {

        //        string msg = "设备已断开,自动重连";

        //        MessAgeChanged(MsgType.NotifyTxt, msg);

        //        if (!asyncLock)

        //        {

        //            asyncLock = true;

        //            this.CurrentDevice.Dispose();

        //            this.CurrentDevice = null;

        //            CurrentService = null;

        //            CurrentWriteCharacteristic = null;

        //            CurrentNotifyCharacteristic = null;

        //            SelectDeviceFromIdAsync(CurrentDeviceMAC);

        //        }

        //    }

        //    else

        //    {

        //        string msg = "设备已连接";

        //        MessAgeChanged(MsgType.NotifyTxt, msg);

        //    }

        //}



        ///// <summary>

        ///// 按MAC地址直接组装设备ID查找设备

        ///// </summary>

        //public async Task SelectDeviceFromIdAsync(string MAC)

        //{

        //    CurrentDeviceMAC = MAC;

        //    CurrentDevice = null;

        //    BluetoothAdapter.GetDefaultAsync().Completed = async (asyncInfo, asyncStatus) =>

        //    {

        //        if (asyncStatus == AsyncStatus.Completed)

        //        {

        //            BluetoothAdapter mBluetoothAdapter = asyncInfo.GetResults();

        //            byte[] _Bytes1 = BitConverter.GetBytes(mBluetoothAdapter.BluetoothAddress);//ulong转换为byte数组

        //            Array.Reverse(_Bytes1);

        //            string macAddress = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();

        //            string Id = "BluetoothLE#BluetoothLE" + macAddress + "-" + MAC;

        //            await Matching(Id);

        //        }

        //    };

        //}



        ///// <summary>

        ///// 设置特征对象为接收通知对象

        ///// </summary>

        ///// <param name="characteristic"></param>

        ///// <returns></returns>

        //public async Task EnableNotifications(GattCharacteristic characteristic)

        //{

        //    string msg = "收通知对象=" + CurrentDevice.ConnectionStatus;

        //    this.MessAgeChanged(MsgType.NotifyTxt, msg);



        //    characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(CHARACTERISTIC_NOTIFICATION_TYPE).Completed = async (asyncInfo, asyncStatus) =>

        //    {

        //        if (asyncStatus == AsyncStatus.Completed)

        //        {

        //            GattCommunicationStatus status = asyncInfo.GetResults();

        //            if (status == GattCommunicationStatus.Unreachable)

        //            {

        //                msg = "设备不可用";

        //                this.MessAgeChanged(MsgType.NotifyTxt, msg);

        //                if (CurrentNotifyCharacteristic != null && !asyncLock)

        //                {

        //                    await this.EnableNotifications(CurrentNotifyCharacteristic);

        //                }

        //            }

        //            asyncLock = false;

        //            msg = "设备连接状态" + status;

        //            this.MessAgeChanged(MsgType.NotifyTxt, msg);

        //        }

        //    };

        //}



        ///// <summary>

        ///// 接受到蓝牙数据

        ///// </summary>

        //private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)

        //{

        //    byte[] data;

        //    CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out data);

        //    string str = BitConverter.ToString(data);

        //    this.MessAgeChanged(MsgType.BleData, str, data);

        //}



        ///// <summary>

        ///// 发送数据接口

        ///// </summary>

        ///// <returns></returns>

        //public async Task Write(byte[] data)

        //{

        //    if (CurrentWriteCharacteristic != null)

        //    {

        //        CurrentWriteCharacteristic.WriteValueAsync(CryptographicBuffer.CreateFromByteArray(data), GattWriteOption.WriteWithResponse);

        //        string str = "发送数据：" + BitConverter.ToString(data);

        //        this.MessAgeChanged(MsgType.BleData, str, data);

        //    }



        //}




        //存储检测的设备MAC。
        public string CurrentDeviceMAC { get; set; }
        //存储检测到的设备。
        public BluetoothLEDevice CurrentDevice { get; set; }
        //存储检测到的主服务。
        public GattDeviceService CurrentService { get; set; }
        //存储检测到的写特征对象。
        public GattCharacteristic CurrentWriteCharacteristic { get; set; }
        //存储检测到的通知特征对象。
        public GattCharacteristic CurrentNotifyCharacteristic { get; set; }

        public string ServiceGuid { get; set; }

        public string WriteCharacteristicGuid { get; set; }
        public string NotifyCharacteristicGuid { get; set; }


        private const int CHARACTERISTIC_INDEX = 0;
        //特性通知类型通知启用
        private const GattClientCharacteristicConfigurationDescriptorValue CHARACTERISTIC_NOTIFICATION_TYPE = GattClientCharacteristicConfigurationDescriptorValue.Notify;


        private Boolean asyncLock = false;

        private DeviceWatcher deviceWatcher;

        private List<BluetoothLEDevice> DeviceList = new List<BluetoothLEDevice>();


        BluetoothLEAdvertisementWatcher watcher;
        //定义一个委托
        public delegate void eventRun(MsgType type, string str, byte[] data = null);
        //定义一个事件
        public event eventRun ValueChanged;

        public delegate void DeviceRun(MsgType type, string str, string Id);
        //定义一个事件
        public event DeviceRun DeviceChanged;

        private static BleCore bluetooth;
        public static BleCore shareInstance()
        {
            if(bluetooth == null)
            {
                bluetooth = new BleCore("0000ff12-0000-1000-8000-00805f9b34fb", "0000ff01-0000-1000-8000-00805f9b34fb", "0000ff02-0000-1000-8000-00805f9b34fb");
            }
            return bluetooth;
        }


        private BleCore(string serviceGuid, string writeCharacteristicGuid, string notifyCharacteristicGuid)
        {
            ServiceGuid = serviceGuid;
            WriteCharacteristicGuid = writeCharacteristicGuid;
            NotifyCharacteristicGuid = notifyCharacteristicGuid;
        }

        public void StopBleDeviceWatcher()
        {
            if(watcher != null)
                 watcher.Stop();
        }
        /// <summary>
        /// 搜索蓝牙设备
        /// </summary>
        /// 
        public void StartBleDeviceWatcher()
        {
            //if(watcher == null)
            {
                watcher = new BluetoothLEAdvertisementWatcher();

                watcher.ScanningMode = BluetoothLEScanningMode.Active;

                // only activate the watcher when we're recieving values >= -80
                watcher.SignalStrengthFilter.InRangeThresholdInDBm = -80;

                // stop watching if the value drops below -90 (user walked away)
                watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -100;

                // register callback for when we see an advertisements
                watcher.Received += OnAdvertisementReceived;

                // wait 5 seconds to make sure the device is really out of range
                watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);
                watcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(2000);

            }

            // starting watching for advertisements
            watcher.Start();
            string msg = "自动发现设备中..";

            if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, msg);
        }
        private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress).Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    if (asyncInfo.GetResults() == null)
                    {

                        if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, "没有搜到可用设备");
                    }
                    else
                    {
                        BluetoothLEDevice currentDevice = asyncInfo.GetResults();

                        Boolean contain = false;
                        //foreach (BluetoothLEDevice device in DeviceList)//过滤重复的设备
                        //{
                        //    if (device.DeviceId == currentDevice.DeviceId)
                        //    {
                        //        contain = true;
                        //    }
                        //}
                       // if (!contain)
                        {
                            byte[] _Bytes1 = BitConverter.GetBytes(currentDevice.BluetoothAddress);
                            Array.Reverse(_Bytes1);

                         //   this.DeviceList.Add(currentDevice);
                           // this.MessAgeChanged(MsgType.NotifyTxt, "发现设备：" + currentDevice.Name + "  address:" + BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower());
                            //this.DeviceWatcherChanged(MsgType.BleDevice, currentDevice);
                            DeviceChanged(MsgType.NotifyTxt, currentDevice.Name, BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower());
                        }
                    }

                }
            };

          }
            public void StartBleDeviceWatcher2()
        {

            string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" };
            string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";

            deviceWatcher =
                    DeviceInformation.CreateWatcher(
                        aqsAllBluetoothLEDevices,
                        requestedProperties,
                        DeviceInformationKind.AssociationEndpoint);

            // Register event handlers before starting the watcher.
            deviceWatcher.Added += DeviceWatcher_Added;
            deviceWatcher.Stopped += DeviceWatcher_Stopped;
            deviceWatcher.Start();
            string msg = "自动发现设备中..";
            Console.WriteLine("自动发现设备中.."+ DateTime.Now);
            if (ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, msg);
        }


        private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
        {
            string msg = "自动发现设备停止";
            Console.WriteLine(msg + DateTime.Now);
            if (ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, msg);
        }

        private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
        {
            DeviceChanged(MsgType.NotifyTxt,args.Name,args.Id);


            if (CurrentDeviceMAC != null && args.Id.EndsWith(CurrentDeviceMAC))
            {
                await  Matching(args.Id);
            }
            Console.WriteLine("DeviceWatcher_Added"+args.Id + DateTime.Now);

        }

        /// <summary>
        /// 按MAC地址查找系统中配对设备
        /// </summary>
        /// <param name="MAC"></param>
        public async Task SelectDevice(string MAC)
        {
            CurrentDeviceMAC = MAC;
            CurrentDevice = null;
            DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()).Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    DeviceInformationCollection deviceInformation = asyncInfo.GetResults();
                    foreach (DeviceInformation di in deviceInformation)
                    {
                        await Matching(di.Id);
                    }
                    if (CurrentDevice == null)
                    {
                        string msg = "正在查找设备";
                        Console.WriteLine(msg + DateTime.Now);
                        if (ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, msg);
                        StartBleDeviceWatcher();
                    }
                }
            };
        }
        /// <summary>
        /// 按MAC地址直接组装设备ID查找设备
        /// </summary>
        /// <param name="MAC"></param>
        /// <returns></returns>
        public async Task SelectDeviceFromIdAsync(string MAC)
        {
            CurrentDeviceMAC = MAC;
            CurrentDevice = null;
            BluetoothAdapter.GetDefaultAsync().Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    BluetoothAdapter mBluetoothAdapter = asyncInfo.GetResults();
                    if(mBluetoothAdapter!= null && mBluetoothAdapter.BluetoothAddress!=null)
                    {
                        byte[] _Bytes1 = BitConverter.GetBytes(mBluetoothAdapter.BluetoothAddress);//ulong转换为byte数组
                        Array.Reverse(_Bytes1);
                        string macAddress = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
                        string Id = "BluetoothLE#BluetoothLE" + macAddress + "-" + MAC;
                        await Matching(Id);
                    }
                    else
                    {
                        if(ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, "蓝牙无法连接");
                    }
          
                }

            };

        }

        public async Task Matching(string Id)
        {

            try
            {
                
                BluetoothLEDevice.FromIdAsync(Id).Completed = async (asyncInfo, asyncStatus) =>
                {
                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        BluetoothLEDevice bleDevice = asyncInfo.GetResults();
                        //在当前设备变量中保存检测到的设备。
                        CurrentDevice = bleDevice;

                        if(CurrentDevice != null)
                        {
                            this.Connect();
                            string msg = "正在查找设备<" + CurrentDeviceMAC + ">..";
                            Console.WriteLine(msg + DateTime.Now);
                            if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, msg);



                            //xgwen
                            await SelectDeviceService();
                        }
                   


                    }
                };
            }
            catch (Exception e)
            {
                string msg = "没有发现设备";
                if(ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, msg);
                StartBleDeviceWatcher();
            }

        }

        public  void Connect()
        {
            //if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, "正在连接设备...");
            if(CurrentDevice != null)
            CurrentDevice.ConnectionStatusChanged += CurrentDevice_ConnectionStatusChanged;
        }


        /// <summary>
        /// 主动断开连接
        /// </summary>
        /// <returns></returns>
        public void Dispose()
        {
            if (CurrentDevice != null)
                CurrentDevice.ConnectionStatusChanged -= CurrentDevice_ConnectionStatusChanged;
            CurrentDeviceMAC = null;
            CurrentService?.Dispose();
            CurrentDevice?.Dispose();
            CurrentDevice = null;
            CurrentService = null;
            CurrentWriteCharacteristic = null;
            CurrentNotifyCharacteristic = null;
            if(ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, "主动断开连接");

        }

        private void CurrentDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
        {
            Console.WriteLine("连接状态："+sender.ConnectionStatus + DateTime.Now);
            if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected || CurrentDeviceMAC == null)
            {
                string msg = "设备已断开";
       
                if (ValueChanged != null) if(ValueChanged!=null)ValueChanged(MsgType.BLEStatus, msg);

                if (!asyncLock)
                {
                    asyncLock = true;
                    if (CurrentDevice != null)
                    {
                        
                        CurrentDevice.Dispose();
                    }
                    if (CurrentService != null)
                    {
                        CurrentService.Dispose();
                    }
                    CurrentDevice = null;
                    CurrentService = null;
                    CurrentWriteCharacteristic = null;
                    CurrentNotifyCharacteristic = null;
                  
                    //SelectDeviceFromIdAsync(CurrentDeviceMAC);
                }

            }
            else
            {
                string msg = "设备已连接";

                if (ValueChanged != null)  ValueChanged(MsgType.BLEStatus, msg);

                if (CurrentWriteCharacteristic != null && CurrentWriteCharacteristic != null)
                    if (ValueChanged != null) ValueChanged(MsgType.ChOK, msg);

            }
        }
        /// <summary>
        /// 按GUID 查找主服务
        /// </summary>
        /// <param name="characteristic">GUID 字符串</param>
        /// <returns></returns>
        public async Task SelectDeviceService()
        {
            Console.WriteLine("SelectDeviceService" + DateTime.Now);
            Guid guid = new Guid(ServiceGuid);
            // CurrentDevice.GetGattServicesForUuidAsync(guid).Completed = (asyncInfo, asyncStatus) =>
           
            CurrentDevice.GetGattServicesAsync().Completed = (asyncInfo, asyncStatus) =>
             
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    try
                    {
                        GattDeviceServicesResult result = asyncInfo.GetResults();

                        foreach(GattDeviceService s in result.Services)
                        {
                       
                            if (s.Uuid.Equals(guid))
                            {
                                string msg = "正在查找服务...";
                                if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, msg);
                                CurrentService = s;// result.Services[CHARACTERISTIC_INDEX];
                                if (CurrentService != null)
                                {
                             
                                    //{
                                        asyncLock = true;
                                       GetCurrentWriteCharacteristic();
                                    //    // GetCurrentNotifyCharacteristic();
                                      

                                    //}
                                    break;

                                }
                                
                                
                            }
                            else
                            {

                            }
                        }

                        //if (result.Services.Count > 0)
                        //{
                        //    string msg = "正在连接服务...";
                        //    if(ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, msg);
                        //    CurrentService = result.Services[CHARACTERISTIC_INDEX];
                        //    if (CurrentService != null)
                        //    {
                        //        asyncLock = true;
                        //        GetCurrentWriteCharacteristic();
                        //        GetCurrentNotifyCharacteristic(); 

                        //    }

                        //}
                        //else
                        if(CurrentService == null)
                        {
                            string msg = "没有发现服务，请重试";
                            if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, msg);
                            // SelectDeviceService();
                        }
                    }
                    catch (Exception e)
                    {
                        if(ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, "没有发现服务,自动重试中");
                        SelectDeviceService();

                    }
                }
                else
                {
                    if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, "没有发现服务,自动重试中");
                    SelectDeviceService();
                }
            };
        }


        /// <summary>
        /// 设置写特征对象。
        /// </summary>
        /// <returns></returns>
        public async Task GetCurrentWriteCharacteristic()
        {
            Console.WriteLine("GetCurrentWriteCharacteristic" + DateTime.Now);

            if (CurrentWriteCharacteristic != null && CurrentNotifyCharacteristic != null)
            {
                if (ValueChanged != null)
                {


                    if (CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                    {


                        ValueChanged(MsgType.BLEStatus, "设备已连接");
                    }
                    ValueChanged(MsgType.ChOK, "设备已就绪");


                }

                return;
            }
            
                string msg = "";
            Guid guid =  new Guid(WriteCharacteristicGuid);
            Guid guid2 = new Guid(NotifyCharacteristicGuid);
            // CurrentService.GetCharacteristicsForUuidAsync(guid).Completed = async (asyncInfo, asyncStatus) =>
            CurrentService.GetCharacteristicsAsync().Completed = async (asyncInfo, asyncStatus) =>
            {
               
                if (asyncStatus == AsyncStatus.Completed)
                {
                    GattCharacteristicsResult result = asyncInfo.GetResults();

                    Console.WriteLine("特征值数量"+ result.Characteristics.Count +"   " + DateTime.Now);
                    int count = 0;
                    foreach(GattCharacteristic ch in result.Characteristics)
                    {
                        if (ch.Uuid.Equals(guid))
                        {
                            CurrentWriteCharacteristic = ch;// result.Characteristics[CHARACTERISTIC_INDEX];
                           // Console.WriteLine(CurrentWriteCharacteristic.Uuid);
                            msg = "查找写特征对象";
                            if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, msg);

                            count++;
                            if (count == 2)
                            {


                                if (CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                                {


                                    ValueChanged(MsgType.BLEStatus, "设备已连接");
                                }
                                ValueChanged(MsgType.ChOK, "设备已就绪");

                                break;
                            }
                               
                        }
                        else if (ch.Uuid.Equals(guid2))
                        {


                            {
                                msg = "查找通知对象";

                                if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, msg);
                                CurrentNotifyCharacteristic = ch;// result.Characteristics[CHARACTERISTIC_INDEX];
                             //   Console.WriteLine(CurrentNotifyCharacteristic.Uuid);
                                CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;
                                CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
                                await EnableNotifications(CurrentNotifyCharacteristic);

                                count++;
                                if (count == 2)
                                {
                                   
                                    if (ValueChanged != null)
                                    {


                                        if (CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                                        {


                                            ValueChanged(MsgType.BLEStatus, "设备已连接");
                                        }
                                        ValueChanged(MsgType.ChOK, "设备已就绪");


                                    }
                                    break;
                                }
                            }
                        }

                    }

                    if(CurrentWriteCharacteristic == null)
                        {
                        msg = "没有发现写特征对象";
                        Console.WriteLine(msg + DateTime.Now);
                        if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, msg);
                         await GetCurrentWriteCharacteristic();
                    }

                    if(CurrentNotifyCharacteristic == null)
                    {
                        msg = "没有发现通知特征对象";
                        Console.WriteLine(msg + DateTime.Now);
                        if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, msg);
                        await GetCurrentWriteCharacteristic();
                    }
                }
            };
        }




        /// <summary>
        /// 发送数据接口
        /// </summary>
        /// <param name="characteristic"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task Write(byte[] data)
        {
            if (CurrentWriteCharacteristic != null)
            {
                Console.WriteLine("SEND："+ TLJConvert.byteToHexStr(data));
                CurrentWriteCharacteristic.WriteValueAsync(CryptographicBuffer.CreateFromByteArray(data), GattWriteOption.WriteWithoutResponse);
            }

        }

        /// <summary>
        /// 设置通知特征对象。
        /// </summary>
        /// <returns></returns>
        public async Task GetCurrentNotifyCharacteristic()
        {
            string msg = "";
            Guid guid = new Guid(NotifyCharacteristicGuid);
            CurrentService.GetCharacteristicsForUuidAsync(guid).Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    GattCharacteristicsResult result = asyncInfo.GetResults();
     
                    if (result.Characteristics.Count > 0)
                    {
                        msg = "通知特征对象已找到";
                        if(ValueChanged!=null)ValueChanged(MsgType.ChOK, msg);
                        CurrentNotifyCharacteristic = result.Characteristics[CHARACTERISTIC_INDEX];
                        Console.WriteLine(CurrentNotifyCharacteristic.Uuid);
                        CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;
                        CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
                        await EnableNotifications(CurrentNotifyCharacteristic);

                    }
                    else
                    {
                        msg = "没有发现通知特征对象";
                        if(ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, msg);
                       // await GetCurrentNotifyCharacteristic();
                    }
                }

                
            };

            //先找到再获取连接状态
           // this.Connect();
        }

        /// <summary>
        /// 设置特征对象为接收通知对象
        /// </summary>
        /// <param name="characteristic"></param>
        /// <returns></returns>
        public async Task EnableNotifications(GattCharacteristic characteristic)
        {
            string msg;
             msg = "打开通知对象" ;
            //if(ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, msg);
            Console.WriteLine(msg + DateTime.Now);

           characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(CHARACTERISTIC_NOTIFICATION_TYPE).Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    GattCommunicationStatus status = asyncInfo.GetResults();
                    if (status == GattCommunicationStatus.Unreachable)
                    {
                        msg = "设备不可用";
                        if(ValueChanged!=null)ValueChanged(MsgType.NotifyTxt, msg);
                        if (CurrentNotifyCharacteristic != null && !asyncLock)
                        {
                            await EnableNotifications(CurrentNotifyCharacteristic);
                        }
                    }
                    else if(status == GattCommunicationStatus.Success)
                    {
                        msg = "开启设备通知";
                        if (ValueChanged != null) ValueChanged(MsgType.NotifyTxt, msg);
                    }
                    asyncLock = false;
              
                }
            };

            this.Connect();
        }

        private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            byte[] data;
            CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out data);
            string str = BitConverter.ToString(data);
            //xgwen
            if(ValueChanged!=null)ValueChanged(MsgType.BLEData, str, data);

        }

    }

    public enum MsgType
    {
        NotifyTxt,
        ChOK,//特征值已ok
        BLEStatus,//特征值已ok
        BLEData
    }

}
